package deep8jvmdvm;

/*
synchronized

synchronized 可以用来修饰以下 3 个层面：

修饰实例方法；

修饰静态类方法；
如果 synchronized 修饰的是静态方法，则锁对象是当前类的 Class 对象。因此即使在不同线程中调用不同实例对象，也会有互斥效果。


修饰代码块。
 */

import utils.PrintlnUtils;

public class TestSynchronized4 {

    public static void main(String[] args) {
        TestSynchronized4 testSynchronized1 = new TestSynchronized4();
        TestSynchronized4 testSynchronized2 = new TestSynchronized4();

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                testSynchronized1.printLog();
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                testSynchronized2.printLog();
            }
        });
        thread1.start();
        thread2.start();

    }

    public static synchronized void printLog() {
        for (int i = 0; i < 5; i++) {
            PrintlnUtils.println(Thread.currentThread().getName() + " is printing " + i);
        }
    }


     /*
            执行后的打印效果如下：

             Thread-0 is printing 0

            Thread-0 is printing 1

            Thread-0 is printing 2

            Thread-0 is printing 3

            Thread-0 is printing 4

            Thread-1 is printing 0

            Thread-1 is printing 1

            Thread-1 is printing 2

            Thread-1 is printing 3

            Thread-1 is printing 4

            可以看出，两个线程还是依次执行的。

         */

}
